package com.tcwlkj.uuService.ui;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.baidu.overlay.BikingRouteOverlay;
import com.tcwlkj.uuService.baidu.overlay.OverlayManager;
import com.tcwlkj.uuService.model.Message;
import com.tcwlkj.uuService.model.OrderModel;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/11/6 0006.
 */
public class OrderMapActivity extends BaseActivity implements BaiduMap.OnMapClickListener,
        OnGetRoutePlanResultListener {
    @Bind(R.id.id_bmapView)
    MapView map_view;
    @Bind(R.id.tv_base_right)
    TextView tv_base_right;
    /**
     * 地图实例
     */
    private BaiduMap mBaiduMap;
    //    百度地图路径规划
    int nodeIndex = -1; // 节点索引,供浏览节点时使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;
    // 搜索相关
    RoutePlanSearch mSearch = null;
    LatLng lat_start, lat_end,lat_current;
    private OrderModel orderModel;
    /**
     * 定位的客户端
     */
    private LocationClient mLocationClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_map);
        ButterKnife.bind(this);
        initview();
        initBaiduMap();
    }
    private void initview() {
        orderModel = (OrderModel) getIntent().getSerializableExtra("orderModel");
        changeTitle("订单地图");
        tv_base_right.setVisibility(View.VISIBLE);
        tv_base_right.setText("开启导航");
        map_view.removeViewAt(1);
        lat_current=new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),ChcheUtils.getInstance().getLocationModel().getLng());
    }

    @OnClick({R.id.img_location,R.id.tv_base_right})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_location:
                if (lat_current == null) {
                    return;
                } else {
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(lat_current)
                            .zoom(18)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.animateMapStatus(mMapStatusUpdate);
                }
                break;
            case R.id.tv_base_right:
                Intent intent;
                if(isAvilible(baseContext,"com.baidu.BaiduMap")){
                    try {
                        if(orderModel.getSendType().equals("40")||orderModel.getSendType().equals("50")){//帮排
                            intent = Intent.getIntent("intent://map/direction?" +
                                    //"origin=latlng:"+qiLat+","+qiLng+"|name:起点"+ //起点  此处不传值默认选择当前位置
                                    "destination=latlng:"+orderModel.getBegLocLat()+","+orderModel.getBegLocLng()+"|name:我的目的地"+        //终点
                                    "&mode=biking&" +          //导航路线方式
                                    "region=北京" +           //
                                    "&src=慧医#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                            baseContext.startActivity(intent); //启动调用
                        }else if(Integer.parseInt(orderModel.getState())>=4){//买送取
                            intent = Intent.getIntent("intent://map/direction?" +
                                    //"origin=latlng:"+orderModel.getBegLocLat()+","+orderModel.getBegLocLng()+"|name:起点"+ //起点  此处不传值默认选择当前位置
                                    "destination=latlng:"+orderModel.getEndLocLat()+","+orderModel.getEndLocLng()+"|name:我的目的地"+        //终点
                                    "&mode=biking&" +          //导航路线方式
                                    "region=北京" +           //
                                    "&src=慧医#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                            baseContext.startActivity(intent); //启动调用
                        }else {
                            intent = Intent.getIntent("intent://map/direction?" +
                                    //"origin=latlng:"+orderModel.getBegLocLat()+","+orderModel.getBegLocLng()+"|name:起点"+ //起点  此处不传值默认选择当前位置
                                    "destination=latlng:"+orderModel.getBegLocLat()+","+orderModel.getBegLocLng()+"|name:我的目的地"+        //终点
                                    "&mode=biking&" +          //导航路线方式
                                    "region=北京" +           //
                                    "&src=慧医#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                            baseContext.startActivity(intent); //启动调用
                        }
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                }else {
                    ToastUtil.getInstance().show("您未安装百度地图");
                }
                break;
        }
    }
    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    private void initBaiduMap() {
        mBaiduMap = map_view.getMap();
        mBaiduMap.setMyLocationEnabled(true);

        initOver(ChcheUtils.getInstance().getLocationModel().getLat(),
                ChcheUtils.getInstance().getLocationModel().getLng());
        if(orderModel.getSendType().equals("10")||orderModel.getSendType().equals("20")||orderModel.getSendType().equals("30")){
            lat_start = new LatLng(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
            lat_end = new LatLng(Double.parseDouble(orderModel.getEndLocLat()), Double.parseDouble(orderModel.getEndLocLng()));

        }else if(orderModel.getSendType().equals("40")||orderModel.getSendType().equals("50")){
            lat_start = new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),ChcheUtils.getInstance().getLocationModel().getLng());
            lat_end = new LatLng(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
        }
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        showlines();
    }
    private void initOver(double a, double b) {
        //定义Maker坐标点
        LatLng point = new LatLng(a, b);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.dangqianweizhi);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    private void initErrorOver(double a, double b) {
        //定义Maker坐标点
        LatLng point = new LatLng(a, b);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.dingweizhi);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    private void showlines() {
        // 重置浏览节点的路线数据
        route = null;
        //mBaiduMap.clear();
//        处理搜索按钮响应
//        设置起终点信息，对于tranist search 来说，城市名无意义
        PlanNode stNode = PlanNode.withLocation(lat_start);
        PlanNode enNode = PlanNode.withLocation(lat_end);
        mSearch.bikingSearch((new BikingRoutePlanOption())
                .from(stNode).to(enNode));

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
        if(bikingRouteResult.error==SearchResult.ERRORNO.RESULT_NOT_FOUND){
            LatLng ll = new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),
                    ChcheUtils.getInstance().getLocationModel().getLng());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(17.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            initErrorOver(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
            //initOver(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
            return;
        }
        if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(OrderMapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            return;
        }
        if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            route = bikingRouteResult.getRouteLines().get(0);
            BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);
            routeOverlay = overlay;
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(bikingRouteResult.getRouteLines().get(0));//设置路线数据
            overlay.addToMap();//将所有overlay添加到地图中
            overlay.zoomToSpan(); //缩放地图
        }

        MapStatus newMapStatus = new MapStatus.Builder().target(lat_current).zoom(16).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(newMapStatus);
        mBaiduMap.animateMapStatus(mMapStatusUpdate, 250);
    }
    private class MyBikingRouteOverlay extends BikingRouteOverlay {

        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }
        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.mipmap.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.mipmap.icon_en);
            }
            return null;
        }
    }

}
